package com.sailorj.medical.domain.family;

import java.sql.Connection;

import com.sailorj.medical.util.MyTime;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import com.sailorj.medical.database.DbUtil;
import com.sailorj.medical.domain.area.Area;
import com.sailorj.medical.exception.DbException;

public class Family {
	
	private static final Logger LOG = LogManager.getLogger(Family.class);
	private String familycode;
	private String familyname;
	private String IDcard;
	private String familyaddr;
	private String familynumber;
	private String familystate;
	private Timestamp createtime;
	private String userid;
	private Area area;
	private String familyteam;

	public Family() {
		super();
	}

	public Family(String familycode, String familyname, String iDcard, String familyaddr, String familynumber,
			String familystate, Timestamp createtime, String userid, Area area, String familyteam) {
		super();
		this.familycode = familycode;
		this.familyname = familyname;
		IDcard = iDcard;
		this.familyaddr = familyaddr;
		this.familynumber = familynumber;
		this.familystate = familystate;
		this.createtime = createtime;
		this.userid = userid;
		this.area = area;
		this.familyteam = familyteam;
	}

	public Family(String familycode, String familyname, String iDcard, String familyaddr, String familynumber,
			String familystate, Area area, String familyteam) {
		super();
		this.familycode = familycode;
		this.familyname = familyname;
		IDcard = iDcard;
		this.familyaddr = familyaddr;
		this.familynumber = familynumber;
		this.familystate = familystate;
		this.area = area;
		this.familyteam = familyteam;
	}

	public String getFamilycode() {
		return familycode;
	}

	public void setFamilycode(String familycode) {
		this.familycode = familycode;
	}

	public String getFamilyname() {
		return familyname;
	}

	public void setFamilyname(String familyname) {
		this.familyname = familyname;
	}

	public String getIDcard() {
		return IDcard;
	}

	public void setIDcard(String iDcard) {
		IDcard = iDcard;
	}

	public String getFamilyaddr() {
		return familyaddr;
	}

	public void setFamilyaddr(String familyaddr) {
		this.familyaddr = familyaddr;
	}

	public String getFamilynumber() {
		return familynumber;
	}

	public void setFamilynumber(String familynumber) {
		this.familynumber = familynumber;
	}

	public String getFamilystate() {
		return familystate;
	}

	public void setFamilystate(String familystate) {
		this.familystate = familystate;
	}

	public Timestamp getCreatetime() {
		return createtime;
	}

	public void setCreatetime(Timestamp createtime) {
		this.createtime = createtime;
	}

	public String getUserid() {
		return userid;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public Area getArea() {
		return area;
	}

	public void setArea(Area area) {
		this.area = area;
	}

	public String getFamilyteam() {
		return familyteam;
	}

	public void setFamilyteam(String familyteam) {
		this.familyteam = familyteam;
	}

	/**
	 * 自动生成家庭编号
	 */
	private String createFamily_code() throws SQLException {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String areacode = this.area.getAreacode();
		String sql = "select max(familycode) from t_family where areacode like'" + areacode + "%'";

		try {
			conn = DbUtil.getConn();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			String maxcode = "";
			Integer number = 1;
			if (rs.next()) {
				maxcode = rs.getString(1);
			}

			if (maxcode != null) {
				int beginIndex = maxcode.length() - 2;
				String no = maxcode.substring(beginIndex);
				number = Integer.parseInt(no);
				++number;
				// 使用0补足位数
				no = String.format("%02d", number);
				maxcode = this.area.getAreacode() + no;
			} else {
				String no = String.format("%02d", number);
				maxcode = this.area.getAreacode() + no;
			}
			return maxcode;
		} catch (SQLException e) {

			throw e;
		} finally {
			DbUtil.close(rs, pstmt, conn);
		}
	}

	/**
	 *  生成组编号
	 */
	@SuppressWarnings("unused")
	private String createFamilyteam() {
		String familyteam = "";
		Integer number = 1;
		try {
			familyteam = createFamily_code();
			int beginIndex = familyteam.length() - 2;
			String no = familyteam.substring(beginIndex);
			number = Integer.parseInt(no);
			// 使用0补足位数
			no = String.format("%02d", number);
			familyteam = no;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return familyteam;
	}

	public void addFamily(String familycode, String familyname, String IDcard, String familyaddr, String familynumber,
			String familystate, String userid, Area area, String familyteam) throws Exception {
		Connection conn = null;
		try {
			// 初始化属性
			this.area = area;
			this.familycode = createFamily_code();
			this.familyname = familyname;
			this.IDcard = IDcard;

			this.familyaddr = familyaddr;
			this.familynumber = "1";
			this.familystate = familystate;
			this.userid = userid;
			this.familyteam = createFamilyteam();
			this.createtime = MyTime.getNowForTimestamp();
			// 保存导数据库
			conn = DbUtil.getConn();
			conn.setAutoCommit(false);
			// 调用插入数据库私有方法
			this.saveToDB(conn);
			conn.commit();
		} catch (Exception e) {
			conn.rollback();
			throw e;
		} finally {
			DbUtil.close(conn);
		}

	}

	/**
	 * 插入记录
	 * 
	 * @param connection
	 * @throws SQLException
	 */
	private void saveToDB(Connection connection) throws SQLException {
		PreparedStatement pstmt = null;
		try {

			StringBuffer sqlBuff = new StringBuffer();
			sqlBuff.append(
					"insert into t_family(areacode,familycode,familyname,IDcard,familyaddr,familynumber,familystate,userid,familyteam,createtime)");
			sqlBuff.append("values(?,?,?,?,?,?,?,?,?,?)");
			String sql = sqlBuff.toString();
			pstmt = connection.prepareStatement(sql);
			// 依次设置动态参数的值，注意顺序
			int index = 1;
			pstmt.setString(index++, this.area.getAreacode());// 行政区域编码
			pstmt.setString(index++, this.familycode);
			pstmt.setString(index++, this.familyname);
			pstmt.setString(index++, this.IDcard);

			pstmt.setString(index++, this.familyaddr);// 行政区域编码
			pstmt.setString(index++, this.familynumber);
			pstmt.setString(index++, this.familystate);
			pstmt.setString(index++, this.userid);

			pstmt.setString(index++, this.familyteam);
			pstmt.setTimestamp(index++, this.createtime);
			// 以executeUpdate()执行SQL
			pstmt.executeUpdate();
		} catch (SQLException e) {
			throw e;
		} finally {
			// 只关闭PrepareStatement资源
			if (pstmt != null) {
				pstmt.close();
			}

		}

	}

	/**
	 * 实例化对象
	 * 
	 * @param areacode
	 * @throws DbException
	 */
	public Family(String familycode) throws DbException {
		if (familycode == null) {
			throw new IllegalStateException("家庭档案信息编号不能空");
		}
		try {
			this.familycode = familycode;
			loadDB();
		} catch (SQLException e) {
			throw new DbException("加载id=" + this.getFamilycode() + "家庭档案信息记录失败", e);
		}
	}

	/**
	 * 
	 * @param areaid
	 * @throws SQLException
	 */
	private void loadDB() throws SQLException {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = DbUtil.getConn();
			pstmt = conn.prepareStatement("select * from t_family where familycode=?");
			int index = 1;
			pstmt.setString(index, this.getFamilycode());
			rs = pstmt.executeQuery();
			if (rs.next()) {
				this.area = new Area(rs.getString("areacode"));
				this.familycode = rs.getString("familycode");
				this.familyname = rs.getString("familyname");
				this.IDcard = rs.getString("IDcard");
				this.familyaddr = rs.getString("familyaddr");
				this.familynumber = rs.getString("familynumber");
				this.familyteam = rs.getString("familyteam");
				this.familystate = rs.getString("familystate");
			}
		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(rs, pstmt, conn);
		}
	}

	public void edit() throws SQLException {
		Connection conn = DbUtil.getConn();
		try {
			conn.setAutoCommit(false);
			this.updateToDB(conn);
			conn.commit();
		} catch (SQLException e) {
			conn.rollback();
			throw e;
		} finally {
			DbUtil.close(conn);
		}
	}

	private void updateToDB(Connection conn) throws SQLException {
		PreparedStatement pstmt = null;
		LOG.info("upDB=" + familycode);
		try {
			// 定义构造update SQL语句字符串变量sql
			String sql = "update t_family set familyname=?,IDcard=?,familyaddr=?,familynumber=?,familyteam=?,familystate=? where familycode=?";
			// 创建执行带动态参数的SQL的PreparedStatement pstmt
			pstmt = conn.prepareStatement(sql);
			// 设置动态参数对应的值
			int index = 1;
			pstmt.setString(index++, this.familyname);
			pstmt.setString(index++, this.IDcard);
			pstmt.setString(index++, this.familyaddr);
			pstmt.setString(index++, this.familynumber);

			pstmt.setString(index++, this.familyteam);
			pstmt.setString(index++, this.familystate);
			pstmt.setString(index++, this.familycode);
			int count = pstmt.executeUpdate();

		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(pstmt);
		}

	}

	public void editMenber(String familycode) throws SQLException {
		Connection conn = DbUtil.getConn();
		try {
			conn.setAutoCommit(false);
			this.familycode = familycode;
			this.loadDB();
			int menber = (Integer.valueOf(this.familynumber).intValue()) + 1;
			this.familynumber = String.valueOf(menber);
			;
			this.updateMenberToDB(conn);
			conn.commit();
		} catch (SQLException e) {
			conn.rollback();
			throw e;
		} finally {
			DbUtil.close(conn);
		}
	}

	private void updateMenberToDB(Connection conn) throws SQLException {
		PreparedStatement pstmt = null;
		LOG.info("upDB=" + familycode);
		try {
			// 定义构造update SQL语句字符串变量sql
			String sql = "update t_family set familynumber=? where familycode=?";
			// 创建执行带动态参数的SQL的PreparedStatement pstmt
			pstmt = conn.prepareStatement(sql);
			// 设置动态参数对应的值
			int index = 1;

			pstmt.setString(index++, this.familynumber);

			pstmt.setString(index++, this.familycode);
			int count = pstmt.executeUpdate();

		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(pstmt);
		}

	}

	public void del(String familycode) throws SQLException {
		LOG.info("del=" + familycode);
		Connection conn = null;
		try {
			// 1:对象属性赋值
			this.familycode = familycode;
			conn = DbUtil.getConn();
			// 2；调用delFromDB方法
			delFromDB(conn);
		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(conn);
		}

	}

	private void delFromDB(Connection conn) throws SQLException {
		PreparedStatement pstmt = null;
		try {
			LOG.info("delDB=" + familycode);
			// 定义构造插入SQL语句字符串变量sql
			String sql = "delete from t_family where familycode=?";
			// 创建执行带动态参数的SQL的PreparedStatement pstmt
			pstmt = conn.prepareStatement(sql);
			// 设置动态参数对应的值
			int index = 1;
			pstmt.setString(index++, this.familycode);

			int count = pstmt.executeUpdate();

		} catch (SQLException e) {
			throw e;
		} finally {
			DbUtil.close(pstmt);

		}

	}
}
